package com.eapi.project.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eapi.project.annotation.AuthCheck;
import com.eapi.project.common.*;
import com.eapi.project.constant.CommonConstant;
import com.eapi.project.constant.UserConstant;
import com.eapi.project.exception.BusinessException;
import com.eapi.project.model.dto.interfaceinfo.*;
import com.eapi.project.model.entity.Invokerecord;
import com.eapi.project.service.*;

import com.eapi.eapicommom.model.entity.InterfaceInfo;
import com.eapi.eapicommom.model.entity.User;
import com.eapi.project.model.entity.Collectrecord;
import com.eapi.project.model.entity.Likerecord;
import com.eapi.project.model.enums.InterfaceInfoStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 接口管理
 */

@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
@CrossOrigin
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private LikerecordService likerecordService;


    @Resource
    private CollectrecordService collectrecordService;

    @Resource
    private InvokerecordService invokerecordService;

    @Resource
    InterfaceinfourlService interfaceinfourlService;
    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                            HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // content 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "content", description);
        // 获取当前登录用户的userRole
        String userRole = userService.getLoginUser(request).getUserRole();
        // 如果用户不是管理员，则只能看到已上线的接口
        if (userRole.equals(UserConstant.DEFAULT_ROLE)) {
            queryWrapper.eq("status",1);
        }
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        if(userRole.equals(UserConstant.DEFAULT_ROLE)){
            interfaceInfoPage.getRecords().forEach(interfaceInfo -> {
                // 获取接口的调用次数
                interfaceInfo.setRelUrl(interfaceInfo.getUrl());
            });
        }
        return ResultUtils.success(interfaceInfoPage);
    }

    // endregion

    /**
     * 发布接口
     * @param idRequest
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = "admin")//该注解校验用户是否是管理员
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest) {
        //判断接口是否存在
        if(idRequest == null || idRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);//抛出参数异常
        }
        // 判断是否存在
        Long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);//未找到数据异常
        }
        //判断接口是否可以调用
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }


    /**
     * 下线接口
     * @param idRequest
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = "admin")//该注解校验用户是否是管理员
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest) {
        //判断接口是否存在
        if(idRequest == null || idRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);//抛出参数异常
        }
        // 判断是否存在
        Long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);//未找到数据异常
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 测试调用
     * @return
     */
   /* @PostMapping("/invoke")
    public BaseResponse<String> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                                    HttpServletRequest request) throws JsonProcessingException {
        //判断接口是否存在
        if(interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);//抛出参数异常
        }
        // JSONUtil.parseObj()
        // 若UserRequestParams参数为String类型
        // String userRequestParams =  interfaceInfoInvokeRequest.getUserRequestParams().toString();
        JSONObject userRequestParams =  JSONUtil.parseObj(interfaceInfoInvokeRequest.getUserRequestParams());
        Long id = interfaceInfoInvokeRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);//未找到数据异常
        }
        if(oldInterfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口已关闭");//未找到数据异常
        }

        Long interfaceid = oldInterfaceInfo.getId();
        switch (interfaceid.toString()) {
            case "1":
                OpenApiClient tempClient = new OpenApiClient();
                com.eapi.eapiclientsdk.model.User user = new com.eapi.eapiclientsdk.model.User();
                user.setName(userRequestParams.getStr("question"));
                String usernameByPost = tempClient.getUsernameByPost(user);
                return ResultUtils.success(usernameByPost);
            case "2":
                TonyiApiClient tonyiApiClient = new TonyiApiClient();
                String result = tonyiApiClient.askQuestion(userRequestParams.getStr("question"));
                System.out.println(result);
                return ResultUtils.success(result);
            case "3":
                WenXinApiClient wenXinApiClient = new WenXinApiClient();
                Question wenxinQuestion = new Question(userRequestParams.getStr("question"));
                String wenxinResult = wenXinApiClient.askQuestion(wenxinQuestion);
                return ResultUtils.success(wenxinResult);
            case "4":
                // 若UserRequestParams参数为json类型，转为map
                // Map<String, String> userRequestParamsMap = (Map<String, String>) interfaceInfoInvokeRequest.getUserRequestParams();
                WeatherApiClient weatherApiClient = new WeatherApiClient();
                WeatherRequest weatherRequest = new WeatherRequest();
               *//* String config = userRequestParamsMap.get("config");
                String city = userRequestParamsMap.get("city");
                String date = userRequestParamsMap.get("date");*//*
                // JSONObject weatherJsonobj = JSONUtil.parseObj(userRequestParams);
                String config = userRequestParams.getStr("config");
                String city = userRequestParams.getStr("city");
                String date = userRequestParams.getStr("date");
                weatherRequest.setConfig(config);
                weatherRequest.setCity(city);
                weatherRequest.setDate(date);
                String weather = weatherApiClient.getWeather(weatherRequest);
                return ResultUtils.success(weather);
            case "5":
                LocationApiClient locationApiClient = new LocationApiClient();
                IP ip = new IP();
                ip.setIp(userRequestParams.getStr("ip"));
                String locationByIP = locationApiClient.getLocationByIP(ip);
                return ResultUtils.success(locationByIP);
            case "6":
                // Map<String, String> pictureToTextMap = (Map<String, String>) interfaceInfoInvokeRequest.getUserRequestParams();
                // JSONObject pictureToTextJsonStr = JSONUtil.parseObj(userRequestParams);
                PictureToTextRequest pictureToTextRequest = new PictureToTextRequest();
                *//*pictureToTextRequest.setQuestion(pictureToTextMap.get("question"));
                pictureToTextRequest.setPicture(pictureToTextMap.get("picture"));*//*
                pictureToTextRequest.setQuestion(userRequestParams.getStr("question"));
                pictureToTextRequest.setPicture(userRequestParams.getStr("picture"));
                PictureToTextApiClient pictureToTextApiClient = new PictureToTextApiClient();
                String text = pictureToTextApiClient.getText(pictureToTextRequest);
                return ResultUtils.success(text);
            case "7":
                // Map<String, String> textToPictureMap = (Map<String, String>) interfaceInfoInvokeRequest.getUserRequestParams();
                TextToPictureRequest textToPictureRequest = new TextToPictureRequest();
                // JSONObject textToPictureJsonStr = JSONUtil.parseObj(userRequestParams);
                //textToPictureRequest.setPrompt();
                String prompt = userRequestParams.getStr("prompt");
                textToPictureRequest.setPrompt(prompt);

                *//*textToPictureRequest.setPrompt(textToPictureMap.get("prompt"));
                textToPictureRequest.setNumber(textToPictureMap.get("number"));*//*
                TextToPictureApiClient textToPictureApiClient = new TextToPictureApiClient();
                String results = textToPictureApiClient.generatePicture(textToPictureRequest);
                return ResultUtils.success(results);
            case "8":
                MedicalAssistantApiClient medicalAssistantApiClient = new MedicalAssistantApiClient();
                Question medicalassistantQuestion = new Question(userRequestParams.getStr("question"));
                String medicalassistantResult = medicalAssistantApiClient.askQuestion(medicalassistantQuestion);
                return ResultUtils.success(medicalassistantResult);
            case "9":
                TranslationRequest translationRequest = new TranslationRequest(userRequestParams.getStr("content"),
                        userRequestParams.getStr("toLanuage"), userRequestParams.getStr("domian"));
                TranslationApiClient translationApiClient = new TranslationApiClient();
                String translate = translationApiClient.translate(translationRequest);
            case "10":
                SmartSound smartSound = new SmartSound();
                smartSound.setPrompt("你好");
                smartSound.setTemplete("sambert-zhilun-v1");
                SambertsoundApiClient sambertsoundApiClient = new SambertsoundApiClient();
                byte[] sound = sambertsoundApiClient.getSound(smartSound);
                String base64Audio = Base64.getEncoder().encodeToString(sound);
                return Base64SoundResponse.buildResponse(base64Audio).getBody();
            default:
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在或请求路径错误");
        }
    }*/
    @PostMapping("/invoke")
    public BaseResponse<String> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        //判断接口是否存在
        List<Long> interfaceIdList = new ArrayList<>();
        interfaceIdList.add(2l);
        interfaceIdList.add(3l);
        interfaceIdList.add(6l);

        Long interfaceId = interfaceInfoInvokeRequest.getId();
        if(interfaceInfoInvokeRequest == null || interfaceId <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);//抛出参数异常
        }
        // JSONUtil.parseObj()
        // 若UserRequestParams参数为String类型
        // String userRequestParams =  interfaceInfoInvokeRequest.getUserRequestParams().toString();
        // JSONObject userRequestParams =  JSONUtil.parseObj(interfaceInfoInvokeRequest.getUserRequestParams());
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(interfaceId);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);//未找到数据异常
        }
        if(oldInterfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口已关闭");//未找到数据异常
        }
        String url = oldInterfaceInfo.getRelUrl();
        Object userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        String jsonStr = JSONUtil.toJsonStr(userRequestParams);
        HttpResponse response = HttpRequest.post(url)
                .contentType("application/json") // 设置请求体的内容类型
                .body(jsonStr) // 设置请求体为字符串
                .execute();
        String body = response.body();
        Long userId = loginUser.getId();

        if(interfaceIdList.contains(interfaceId)){
            int length = body.length();
            double price = length * 0.012;
            // 实际扣费
            Long l = price > 1 ? (long) price : 1;
            Long points = (loginUser.getRemainingPoints() - l);
            loginUser.setRemainingPoints(points);
            // 更新账户余额
            userService.updateById(loginUser);
            // 更新调用记录
            Invokerecord invokerecord = new Invokerecord();
            invokerecord.setInterfaceInfoId(interfaceId);
            invokerecord.setUserId(userId);
            invokerecord.setInvokeCosts(l);
            invokerecord.setInterfaceInfoName(oldInterfaceInfo.getName());
            invokerecord.setDescription(oldInterfaceInfo.getDescription());
            invokerecordService.insertInvoke(invokerecord);
        }

        return ResultUtils.success(body);

    }

    @PostMapping("/like")
    public BaseResponse<String> likeInterfaceInfo(@RequestBody InterfaceInfoLikeRequest interfaceInfoLikeRequest, HttpServletRequest request) {
        //判断请求是否合法
        if(interfaceInfoLikeRequest == null || interfaceInfoLikeRequest.getInterfaceInfoId() <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);//抛出参数异常
        }
        Long interfaceInfoId = interfaceInfoLikeRequest.getInterfaceInfoId();
        // 判断接口是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(interfaceInfoId);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"接口不存在");
        }
        // 判断该用户是否点过赞
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        QueryWrapper<Likerecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("interfaceInfoId",interfaceInfoId);
        Likerecord record = likerecordService.getOne(queryWrapper);
        if(record != null){
            // throw new BusinessException(ErrorCode.PARAMS_ERROR,"请勿重复点赞");
            // 取消点赞
            // 删除数据库中的点赞记录
            likerecordService.removeById(record.getId());

            // 将interfaceInfo中的点赞数减一
            oldInterfaceInfo.setLikes(oldInterfaceInfo.getLikes() - 1);
            interfaceInfoService.updateById(oldInterfaceInfo);
            return ResultUtils.success("点赞已取消");
        }
        else{
            // 执行点赞
            Likerecord likerecord = new Likerecord();
            likerecord.setInterfaceInfoId(interfaceInfoId);
            likerecord.setUserId(userId);
            likerecordService.save(likerecord);
            oldInterfaceInfo.setLikes(oldInterfaceInfo.getLikes() + 1);
            boolean result = interfaceInfoService.updateById(oldInterfaceInfo);
            return ResultUtils.success("点赞成功");
        }
    }

    @PostMapping("/collect")
    public BaseResponse<String> collectInterfaceInfo(@RequestBody InterfaceInfoCollectRequest interfaceInfoCollectRequest, HttpServletRequest request) {
        //判断请求是否合法
        if(interfaceInfoCollectRequest == null || interfaceInfoCollectRequest.getInterfaceInfoId() <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);//抛出参数异常
        }
        Long interfaceInfoId = interfaceInfoCollectRequest.getInterfaceInfoId();
        // 判断接口是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(interfaceInfoId);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"接口不存在");
        }
        // 判断该用户是否收藏过
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        QueryWrapper<Collectrecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("interfaceInfoId",interfaceInfoId);
        Collectrecord record = collectrecordService.getOne(queryWrapper);
        if(record != null){
            collectrecordService.removeById(record.getId());
            // 将interfaceInfo中的点赞数减一
            oldInterfaceInfo.setCollections(oldInterfaceInfo.getCollections() - 1);
            interfaceInfoService.updateById(oldInterfaceInfo);
            return ResultUtils.success("已取消收藏");
            // throw new BusinessException(ErrorCode.PARAMS_ERROR,"您已收藏");
        }
        else{
            // 执行收藏
            Collectrecord collectrecord = new Collectrecord();
            collectrecord.setInterfaceInfoId(interfaceInfoId);
            collectrecord.setUserId(userId);
            collectrecordService.save(collectrecord);
            oldInterfaceInfo.setCollections(oldInterfaceInfo.getCollections() + 1);
            interfaceInfoService.updateById(oldInterfaceInfo);
            return ResultUtils.success("收藏成功");
        }
    }
}
